<?php
class TagMapper{
    protected $table;
    protected $query;

    public function setTable($_table){
        $this->table = $_table;
        $this->query = 'SET NAMES utf8; SET CHARACTER SET utf8';
        return $this;
    }
    public function getTable(){
        return $this->table;
    }

    public function save($tag){
        $arr = array(
            'text'   => $tag->getText(),
        );
        $db = Database::getInstance();
        
        if(null == ($id = $tag->getId())){
            $db->insert('tags', $arr);
        }else{
            $db->update('tags', $arr, $id);
        }
    }

    public function find($id, $tag){
        $db = Database::getInstance();
        //$db = $reg->get('db');
        $data = $db->select('tags', $id);
        //echo $id;
        $tag    ->setText($data['text'])
                ->setId($id)

                ->setMapper($this);
    }

    public function delete($tag){
        $db = Database::getInstance();;
        $db->delete('tags', $tag->getId());
    }

    public function fetchAllTags(){
        $db = Database::getInstance();
        $resultSet = $db->fetchAll('tags');
        //var_dump($resultSet);
        $tags = array();
        $messages = array();
        foreach($resultSet as $one){
            $tag = new TagModel();
            $tag    ->setText($one['text'])
                    ->setId($one['id'])
                    ->setMapper($this);
            $tags[] = $tag;
        }
        return $tags;
    }

    public function fetchAllTagsById($m_id){
        $db = Database::getInstance();
        $resultSet = $db->fetchAll('tag_to_msg WHERE msg_id = ' . $m_id);
        
        //var_dump($resultSet);
        //exit;
        $tags = array();
        $messages = array();
        if(!empty($resultSet)){
            foreach($resultSet as $one){
                $tag = new TagModel();
                $tag = $tag->find($one['tag_id']);
//                $tag    ->setText($one['tag_'])
//                        ->setId($one[])
//                        ->setMapper($this);
                $tags[] = $tag;
            }
        }
        
        return $tags;
    }
}
?>
